import { vipTypeList } from "@/utils/common";
import Https from "@/utils/Https";
import { ProForm, ProFormText, ProTable } from "@ant-design/pro-components";
import {
  Button,
  Descriptions,
  Drawer,
  Form,
  InputNumber,
  Space,
  message,
  Tooltip,
} from "antd";
import TextArea from "antd/es/input/TextArea";
import dayjs from "dayjs";
import { FC, useEffect, useRef, useState } from "react";
import { weekNameList } from "../../interface";
import { calcColumnsTwo } from "../configFile";
import styles from "../styles.less";
const AddReservation: FC<any> = (props) => {
  const { open, onClose, courseInfo, defaultDate, onSuccess } = props;
  const formRef = useRef();
  const [openTwo, setOpenTwo] = useState(false);
  const [userInfo, setUserInfo] = useState<any>({});
  const [loading, setLoading] = useState(false);
  const [maxCount, setMaxCount] = useState(1000);
  const cardTableRef = useRef();
  const [isSave, setIsSave] = useState(true);
  const [currentDeductNum, setCurrentDeductNum] = useState(0);
  //保存排课信息
  const save = async () => {
    let result = await formRef?.current?.validateFields();
    let params = {
      userCardId: userInfo.id,
      courseScheduleId: courseInfo.id,
      remark: result.remark,
      appointPeopleNum: result.appointPeopleNum,
      currentDate: dayjs(defaultDate).format("YYYY-MM-DD"),
    };
    setLoading(true);
    let res = await Https.post("/proxy/appoint/proxyAppointSave", params, true);
    if (res.code == 200) {
      message.success("预约成功");
      onSuccess();
    } else {
      message.error(res.msg);
    }
    setLoading(false);
  };
  //获取选择预约会员列表
  const getList = async (obj) => {
    let records = [];
    let total = 0;
    setLoading(true);
    let params = {
      ...obj,
      courseId: courseInfo.courseId,
      courseScheduleId: courseInfo.id,
    };
    let res = await Https.get(
      "/proxy/appoint/getUsableUserCardList",
      params,
      true
    );
    if (res.code == 200) {
      records = res.data.records;
      total = res.data.total;
    } else {
      message.error(res.msg);
    }
    setLoading(false);
    return { success: true, data: records, total };
  };
  const operate = {
    title: "操作",
    fixed: "right",
    dataIndex: "operator",
    align: "center",
    hideInSearch: true,
    width: 120,
    render: (_, record) => {
      return (
        <a
          onClick={() => {
            setUserInfo(record);
            setOpenTwo(false);
            let currentCardLimit =
              record.vipType == 1
                ? Number(record.currentCardLimit / 100)
                : record.vipType == 3
                ? record.currentCardLimit
                : "";
            let deductNum =
              record.vipType == 1
                ? Number(record.deductNum / 100)
                : record.vipType == 3
                ? record.deductNum
                : "-";
            setCurrentDeductNum(deductNum);
            formRef?.current?.setFieldsValue({
              appointPeopleNum: 1,
              remark: "",
              deductNum: deductNum,
            });
            let maxCount = 1000;
            let MaxLimit;
            let hasSave = true;
            if (record.vipType == 1) {
              MaxLimit = Number(record.currentCardLimit / 100);
              maxCount = Math.floor(MaxLimit / deductNum);
              hasSave = currentCardLimit >= deductNum;
            } else if (record.vipType == 3) {
              maxCount = Math.floor(record.currentCardLimit / deductNum);
              hasSave = currentCardLimit >= deductNum;
            } else {
              maxCount = 1000;
            }
            setIsSave(hasSave);
            setMaxCount(maxCount);
          }}
        >
          选择
        </a>
      );
    },
  };
  useEffect(() => {
    setUserInfo({});
    formRef?.current?.resetFields();
  }, [open]);
  return (
    <>
      <Drawer
        title={`预约团课(${dayjs(defaultDate).format("YYYY-MM-DD")} 周${
          weekNameList[
            dayjs(defaultDate).day() == 0 ? 7 : dayjs(defaultDate).day()
          ]
        })`}
        onClose={() => {
          onClose();
        }}
        destroyOnClose={true}
        maskClosable={true}
        className={styles.AddReservationBox}
        width="60%"
        open={open}
        footer={
          <Space>
            <Button
              onClick={() => {
                onClose();
              }}
              size="large"
            >
              取消
            </Button>
            <Tooltip
              title={
                (!userInfo.id || !isSave) &&
                "未选择预约会员或当前余额不足扣除费用"
              }
            >
              <Button
                onClick={() => {
                  save();
                }}
                disabled={!userInfo.id || !isSave}
                loading={loading}
                size="large"
                type="primary"
              >
                确定
              </Button>
            </Tooltip>
          </Space>
        }
      >
        <Descriptions column={2} title="课程信息" bordered>
          <Descriptions.Item label="课程名称">
            {courseInfo.courseName}
          </Descriptions.Item>
          <Descriptions.Item label="上课时间">
            {dayjs(courseInfo.startTimeSlot).format("HH:mm")}-
            {dayjs(courseInfo.endTimeSlot).format("HH:mm")}
          </Descriptions.Item>
        </Descriptions>
        
        <Descriptions
          column={2}
          title={
            <div>
              会员信息
              <a
                style={{ marginLeft: "10px", fontSize: "14px" }}
                onClick={() => {
                  setOpenTwo(true);
                }}
              >
                选择预约会员
              </a>
            </div>
          }
          bordered
        >
          <Descriptions.Item label="会员名称">
            {userInfo.nickName || "-"}
          </Descriptions.Item>
          <Descriptions.Item label="手机号">
            {userInfo.tel || "-"}
          </Descriptions.Item>
          <Descriptions.Item label="卡号" copyable ellipsis>
            {userInfo.cardNo || "-"}
          </Descriptions.Item>
          <Descriptions.Item label="开卡场馆">
            {userInfo.venueName || "-"}
          </Descriptions.Item>
          <Descriptions.Item label="余额">
            {userInfo.vipType
              ? userInfo.vipType != 2
                ? userInfo.vipType == 1
                  ? Number(userInfo.currentCardLimit) / 100 +
                    vipTypeList[userInfo.vipType].status
                  : userInfo.currentCardLimit +
                    vipTypeList[userInfo.vipType].status
                : "-"
              : "-"}
          </Descriptions.Item>
          <Descriptions.Item label="有效期至">
            {userInfo.effectiveTime
              ? dayjs(userInfo.effectiveTime).format("YYYY-MM-DD")
              : "-"}
          </Descriptions.Item>
        </Descriptions>
        <Descriptions column={2} title="预约信息"></Descriptions>
        <ProForm formRef={formRef} submitter={false} layout="vertical">
          <Form.Item
            label="预约人数"
            name="appointPeopleNum"
            rules={[{ required: true, message: " 请输入预约人数" }]}
          >
            <InputNumber
              style={{ width: "100%" }}
              min={1}
              max={maxCount}
              precision={0}
              controls={false}
              suffix="人"
              placeholder="请输入预约人数"
              disabled={!isSave}
              onChange={(e) => {
                if (userInfo.id && userInfo.vipType != "2") {
                  let sum = currentDeductNum * e;
                  formRef?.current?.setFieldsValue({ deductNum: sum });
                }
              }}
            />
          </Form.Item>
          <ProFormText
            name="deductNum"
            label="扣除费用"
            addonAfter={
              userInfo.vipType
                ? userInfo.vipType != 2
                  ? vipTypeList[userInfo.vipType].status
                  : ""
                : ""
            }
            readonly
          />
          <Form.Item
            label="备注"
            name="remark"
            style={{ width: "100%", marginRight: "0" }}
          >
            <TextArea
              placeholder="请输入备注"
              maxLength={100}
              allowClear
              showCount
              style={{ height: 120, resize: "none" }}
            />
          </Form.Item>
        </ProForm>
      </Drawer>
      <Drawer
        width="60%"
        open={openTwo}
        destroyOnClose={true}
        maskClosable={true}
        title={"选择会员"}
        onClose={() => {
          setOpenTwo(false);
        }}
      >
        {openTwo && (
          <ProTable
            rowKey="id"
            actionRef={cardTableRef}
            pagination={{
              showSizeChanger: true,
            }}
            search={{
              filterType: 'light',
            }}
            loading={loading}
            request={async (params) => {
              return await getList(params);
            }}
            columns={calcColumnsTwo({ operate })}
          />
        )}
      </Drawer>
    </>
  );
};
export default AddReservation;
